//
//  DictionaryExtension.swift
//  PassVPN
//
//  Created by yiwanjun on 2018/1/31.
//  Copyright © 2018年 Maynard. All rights reserved.
//

import Foundation

public extension Dictionary {
    /// Dictionary 转 data
    /// - Returns: data
    func jsonData() -> Data? {
        var data: Data?
        do {
            data = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
        } catch {
            return nil
        }
        return data
    }

    /// Dictionary 转 jsonString
    /// - Returns: jsonString
    func jsonString() -> String? {
        if let data = jsonData() {
            return String(bytes: data, encoding: String.Encoding.utf8)
        } else {
            return nil
        }
    }

    func toJsonString(data: Data) -> String? {
        return String(bytes: data, encoding: String.Encoding.utf8)
    }
}

public extension Dictionary where Key == String, Value == Any {
    // 字典转为按key排序后的json字符串
    var orderedJsonString: String? {
        if !JSONSerialization.isValidJSONObject(self) {
            return nil
        }

        var namedPaird = [String]()
        let sortedKeysAndValues = self.sorted { $0.0 < $1.0 }

        for (key, value) in sortedKeysAndValues {
            if value is [String: Any] {
                namedPaird.append("\"\(key)\":\((value as! [String: Any]).orderedJsonString ?? "")")
            } else if value is [Any] {
                namedPaird.append("\"\(key)\":\(value)")
            } else {
                namedPaird.append("\"\(key)\":\"\(value)\"")
            }
        }
        let returnString = namedPaird.joined(separator: ",")
        return"{\(returnString)}"
    }
}
